<template>
  <div id="app">
    <MyHeader @received="received" :todos="todos"></MyHeader>
    <MyList :todos="todos"></MyList>
    <MyFooter @delDone="delDone" :todos="todos" @reverseSelect="reverseSelect"></MyFooter>
  </div>
</template>

<script>

import MyHeader from './components/MyHeader.vue';
import MyFooter from './components/MyFooter.vue';
import MyList from './components/MyList.vue';
import pubsub from "pubsub-js";

export default {
  name: 'App',
  components: { MyHeader, MyFooter, MyList },
  data () {
    return {
      todos: [],
    }
  },
  computed: {
    todoDone() {
      let doneCount = 0
      this.todos.forEach(todo => {
        if (todo.done == true) {
          doneCount++
        } 
      });
      return doneCount
    },
    todoTotal() {
      return this.todos.length
    },
  },
  methods: { 
    // 向todos列表中添加一个元素    
    received(obj) {
      this.todos.unshift(obj)
    },
    // 删除已经完成的项目
    delDone() {
      this.todos = this.todos.filter( todo => todo.done === false )
    },
    // 全选 or 反选
    reverseSelect(done) {
      this.todos.forEach( todo => todo.done = done )
    },
    // 删除 todo
    delTodo(pubName, id) {
      this.todos = this.todos.filter( todo => todo.id !== id )
    },
    // 更新todo内容title
    updateTodo(id, newTitle) {
      this.todos.forEach(todo => {
        if (todo.id === id) {
          todo.title = newTitle
        }
      })
    },
    // 更新todo勾选
    updateTodoCheck(pubname, id) {
      // pubname 为订阅的名字
      this.todos.forEach((todo) => {
        if (todo.id === id) {
          todo.done = !todo.done
        }
      })
    }
  },
  watch: {
    todos: {
      deep: true,
      handler(value) {
        localStorage.setItem('todos', JSON.stringify(value))
      }
    }
  },
  mounted() {
    this.pubUpdate = pubsub.subscribe('updateTodoCheck', this.updateTodoCheck)
    this.$bus.$on('updateTodo', this.updateTodo)
    this.pubDel = pubsub.subscribe('delTodo', this.delTodo)

    // 读取浏览器缓存
    let local_todos = JSON.parse(localStorage.getItem('todos'))
    if (local_todos != null) {
      this.todos = local_todos
    } 
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubDel)
    pubsub.unsubscribe(this.pubUpdate)
    this.$bus.$off('updateTodo')
  },
}
</script>


<style>
  * {
    margin: 0;
    padding: 0;
  }
  #app {
    border: 1px solid #9c9c9c;
    border-radius: 3px;
    padding: 10px;
    width: 450px;
    height: 300px;
    margin: 30px auto;
  }
  button {
        visibility: hidden;
        color: white;
        border: none;
        background-color: #c63535e8;
        padding: 5px;
        border-radius: 3px;
    }
    button:hover {
        cursor: pointer;
        background-color: #c63535;
    }
    button:active {
        background-color: #c63535e8;
    }
</style>
